import { nextTick } from 'vue'

import { createI18n } from 'vue-i18n'

import moment from "moment"

import type { I18n } from 'vue-i18n'

import { useUserStore } from "@/store/user"

import { Locale } from 'vant'

// 中文简体
import zhCN from './locale/zh-CN.json'

// 英文
import enUS from './locale/en-US.json'

// 泰语
import thTH from './locale/th-TH.json'

export const SUPPORT_LOCALES = ['th-TH', 'zh-CN', 'en-US']

export const SUPPORT_LOCALES_LIST: { text: string, value: string }[] = [
  { text: 'lang.zhCN', value: 'zh-CN' },
  { text: 'lang.enUS', value: 'en-US' },
  { text: 'lang.thTH', value: 'th-TH' },
]

export const SUPPORT_LOCALES_VAL_MAP: { [key in string]: string } = {
  'lang.zhCN': 'zh-CN',
  'lang.enUS': 'en-US',
  'lang.thTH': 'th-TH',
}

export const SUPPORT_LOCALES_MAP: { [key in string]: string } = {
  'zh-CN': 'lang.zhCN',
  'en-US': 'lang.enUS',
  'th-TH': 'lang.thTH'
}

export const i18n = setupI18n({
  locale: 'zh-CN', // 默认语言类型
  fallbackLocale: 'en-US',
  legacy: false, // 如果要支持compositionAPI，此项必须设置为false;
  globalInjection: true,  // 全局注册$t方法
  messages: { 
    'zh-CN': zhCN, // 中文简体
    'en-US': enUS, // 英文
    'th-TH': thTH,  // 泰语
  }
})

export function setupI18n(options: any = { locale: 'zh-CN' }): any {
  const instance = createI18n(options)
  setI18nLanguage(instance, options.locale)
  setVantLanguage(options.locale)
  return instance
}

export async function setVantLanguage(lang: string){
  const language = await import(/* @vite-ignore */`/node_modules/vant/es/locale/lang/${lang}`)
  Locale.use(lang, language.default)
}

export function setI18nLanguage(i18n: any, locale: string) {
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale
  } else {
    i18n.global.locale.value = locale
  }
  document.querySelector('html')?.setAttribute('lang', locale)
  moment.locale(locale.split('-')[0])
}

export async function loadLocaleMessages(i18n: I18n, locale: string) {
  const messages = await import(`./locale/${locale}.json`)
  i18n.global.setLocaleMessage(locale, messages.default)
  return nextTick()
}


export function getI18nLanguage(lang?: string) {
  if(lang) return SUPPORT_LOCALES_MAP[lang]
  return (
    i18n.mode === 'legacy'  ?  
    SUPPORT_LOCALES_MAP[i18n.global.locale] : 
    SUPPORT_LOCALES_MAP[i18n.global.locale.value]
  )
}

export const useLocales = (lang: any) => {
  const store = useUserStore()
  if(typeof lang !== 'string') throw new Error('useLocales function parameter language is incorrect!')
  if(!i18n)  throw new Error('i18n instance is not init!')
  store.setLang(lang)
  moment.locale(lang.split('-')[0])
  setVantLanguage(lang)
  setI18nLanguage(i18n, lang)
}

